import { AppState } from './store/index';
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { Store,select } from '@ngrx/store';
import { fromEvent, Observable } from 'rxjs';
import {filter, map } from "rxjs/operators"
import { addTodo, deleteTodo } from './store/actions/todo.actions';
import { Todo } from './store/reducers/todo.reducer';
import { selectTodos } from './store/selector/todo.selectors';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.components.css']
})
export class AppComponent implements AfterViewInit{
  @ViewChild('AddTodoInput') AddTodoInput!:ElementRef
  public keyword: string;
  todos:Observable<Todo[]>
  constructor(private store:Store<AppState>){
    this.todos =this.store.pipe(select(selectTodos))
  }
  ngAfterViewInit(): void {
    // throw new Error('Method not implemented.');
    fromEvent<KeyboardEvent>(this.AddTodoInput.nativeElement,"keyup").pipe(
      filter(event=>event.key==='Enter'),
      map(event=>(<HTMLInputElement>event.target).value),
      map(title=>title.trim()),
      filter(title=>title!=="")
    ).subscribe(
      title=>{
        this.store.dispatch(addTodo({title}))
        this.AddTodoInput.nativeElement.value=""
      }
    )
  }
  onAdd(){
    if(!this.keyword)return
    this.store.dispatch(addTodo({title:this.keyword}))
    this.keyword=''
  }
  deleteTodo(id:string){
    this.store.dispatch(deleteTodo({id}))
  }
}
